//
//  FTSlideBar.m
//  FoodMaster
//
//  Created by 梁尚嘉 on 2017/1/20.
//  Copyright © 2017年 stree7. All rights reserved.
//

#import "FTSlideBar.h"



#define MARGIN_LEFT_RIGHT FT_SIZE(25)
#define ITEM_INNER_SPACE FT_SIZE(35)




@interface NSAttributedString (SizeRemind)

/**
 *  计算大小
 *  @param size 限制的大小
 *  @return 实际大小
 */
- (CGSize)boundSize:(CGSize)size;

@end

@implementation NSAttributedString (SizeRemind)

- (CGSize)boundSize:(CGSize)size {

    CGSize attrStrSize = CGSizeZero;

    if (self.string.length) {

        NSDictionary *attrDict = [self attributesAtIndex:0
                                          effectiveRange:nil];

        CGRect contentRect = [self.string boundingRectWithSize:size
                                                       options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine)
                                                    attributes:attrDict
                                                       context:nil];
        attrStrSize = contentRect.size;
    }

    return attrStrSize;
}

@end



@interface FTSlideBar ()
@property (nonatomic, strong) NSMutableArray <UIButton*>*items;
@property (nonatomic, strong) UIView *indicatorView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *bottomLine;
@end

@implementation FTSlideBar

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.scrollView.frame = CGRectMake(MARGIN_LEFT_RIGHT, 0, self.bounds.size.width-MARGIN_LEFT_RIGHT*2, self.bounds.size.height);
    self.bottomLine.frame = CGRectMake(0, self.bounds.size.height-.5f, self.bounds.size.width, .5f);
    [self reloadItemsPostion];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self configure];
    }
    return self;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self configure];

    }
    return self;
}

- (void)configure
{
    _items = [NSMutableArray array];

    _bottomLine = [UIView new];
    _bottomLine.backgroundColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1];
    [self addSubview:self.bottomLine];

    _scrollView = [UIScrollView new];
    _scrollView.showsHorizontalScrollIndicator = NO;
    //    _scrollView.bounces = NO;
    [self addSubview:self.scrollView];


    _indicatorView = [UIView new];
    [self.scrollView addSubview:self.indicatorView];
}


- (void)setDataSource:(id<FTSlideBarDataSource>)dataSource
{
    _dataSource = dataSource;
    [self reloadData];
}


- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    _selectedIndex = selectedIndex;
    for (UIButton *item in self.items) {
        item.selected = NO;
    }
    [self moveToSelectedIndex];
    self.items[_selectedIndex].selected = YES;

}

- (void)reloadItemsPostion
{
    for (UIView *item in self.items) {
        CGPoint center = item.center;
        center.y = self.scrollView.bounds.size.height/2;
        [item setCenter:center];
    }
}

- (void)moveToSelectedIndex
{

    //item
    if (self.scrollView.contentSize.width>self.bounds.size.width-2*MARGIN_LEFT_RIGHT) {
        CGFloat destinX = 0;
        if (_selectedIndex== 0) {
            destinX = ITEM_INNER_SPACE;
        }else {
            destinX = CGRectGetMinX(self.items[_selectedIndex].frame) - self.items[_selectedIndex-1].frame.size.width - ITEM_INNER_SPACE;
        }
        if (self.scrollView.contentSize.width - destinX < self.scrollView.bounds.size.width) {
            destinX = destinX - (self.scrollView.bounds.size.width - (self.scrollView.contentSize.width - destinX));
        }

        [self.scrollView setContentOffset:CGPointMake(destinX, 0)
                                 animated:YES];
    }

    //indicatorview
    [UIView animateWithDuration:.3
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.indicatorView.frame = CGRectMake(CGRectGetMinX(self.items[_selectedIndex].frame),
                                                               self.bounds.size.height - FT_SIZE(15),
                                                               self.items[_selectedIndex].bounds.size.width,
                                                               1.5);
                     } completion:nil];
}


- (void)reloadData
{

    if (!self.dataSource) {
        return;
    }
    for (UIView *view in self.items) {
        [view removeFromSuperview];
    }

    self.indicatorView.backgroundColor = [self.dataSource activeColor];

    for (NSUInteger i = 0; i < [self.dataSource numOfItem]; i ++) {
        NSString *title = [self.dataSource itemTitleAtIndex:i];
        UIButton *item = [UIButton new];
        [item.titleLabel setFont:[self.dataSource itemFont]];
        [item setTitle:title forState:UIControlStateNormal];
        [item setTitleColor:[self.dataSource normalColor] forState:UIControlStateNormal];
        [item setTitleColor:[self.dataSource activeColor] forState:UIControlStateSelected];
        [item addTarget:self action:@selector(tapItem:) forControlEvents:UIControlEventTouchUpInside];

        CGFloat x = (i>0?CGRectGetMaxX(self.items[i-1].frame):0) + ITEM_INNER_SPACE;
        CGSize size = [[[NSAttributedString alloc]initWithString:title attributes:@{NSFontAttributeName:item.titleLabel.font}] boundSize:CGSizeMake(999, 999)];
        CGRect frame = CGRectMake(x, 0, size.width, self.bounds.size.height);
        [item setFrame:frame];
        [self.items addObject:item];
        [self.scrollView addSubview:item];
    }

    //内容不足平分宽度
    if (CGRectGetMaxX([self.items lastObject].frame) <= self.bounds.size.width-2*MARGIN_LEFT_RIGHT) {
        CGFloat totalWidth = self.bounds.size.width-2*MARGIN_LEFT_RIGHT;
        self.scrollView.contentSize = CGSizeMake(totalWidth, 0);
        NSUInteger numOfItem = self.items.count;
        CGFloat singleWidth = (totalWidth-(numOfItem-1)*ITEM_INNER_SPACE)/numOfItem;
        for (NSUInteger i = 0; i < numOfItem; i ++) {
            CGFloat x = (i>0?CGRectGetMaxX(self.items[i-1].frame):0) + (i==0?0:ITEM_INNER_SPACE);
            CGSize size = CGSizeMake(singleWidth, self.scrollView.bounds.size.height);
            CGRect frame = CGRectMake(x, 0, size.width, self.bounds.size.height);
            self.items[i].frame = frame;
        }
    }else {
        [self.scrollView setContentSize:CGSizeMake(CGRectGetMaxX([self.items lastObject].frame), 0)];
    }
    [self reloadItemsPostion];


}


- (void)setTitle:(NSString *)title atIndex:(NSUInteger)index
{
    [self.items[index] setTitle:title forState:UIControlStateNormal];
}



#pragma mark - Actions
- (void)tapItem:(UIButton *)item
{
    NSUInteger index = [self.items indexOfObject:item];
    self.selectedIndex = index;

    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectItemAtIndex:)]) {
        [self.delegate didSelectItemAtIndex:self.selectedIndex];
    }
}


@end

